<template>
  <wf-el-drawer title="企业认证" :visible.sync="visible" size="560px" :before-close="beforeClose">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <div class="org-auth-drawer-box">
        <div class="org-auth-drawer-box-cont">
          <el-form-item label="企业名称：" prop="organizationName">
            <el-input
              v-model="form.organizationName"
              placeholder="请输入企业名称"
              :maxlength="50"
            ></el-input>
          </el-form-item>
          <el-form-item label="企业地址：" prop="address">
            <div class="org-auth-area">
              <el-cascader
                :value="selectedArea"
                style="width:100%"
                :options="areaOptions"
                @change="handleAreaChange"
              ></el-cascader>
            </div>
            <el-input
              v-model.trim="form.address"
              type="textarea"
              :rows="2"
              placeholder="请填写详细地址（最多可输入25个字符）"
              :maxlength="25"
            ></el-input>
          </el-form-item>

          <el-form-item label="证件号码：" prop="creditCode">
            <el-input
              v-model.trim="form.creditCode"
              placeholder="统一社会信用代码/组织机构代码"
            ></el-input>
          </el-form-item>
          <el-form-item ref="uploadImg" label="营业执照：" prop="licenseImg">
            <div class="org-auth-upload-tip">
              <span>支持格式：jpg、jpeg、png、bmp、gif</span>
              <span>图片要求：信息清晰可见，内容真实有效、不得有任何涂抹修改</span>
              <span>文件大小：不超过5M</span>
            </div>
            <el-upload
              class="org-auth-upload"
              action="customUpload"
              :multiple="false"
              :file-list="fileList"
              :before-upload="beforeUpload"
              :on-remove="onUploadRemove"
              :limit="1"
            >
              <el-button type="text">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="法人代表：" prop="legalPerson">
            <el-input
              v-model="form.legalPerson"
              placeholder="法人代表姓名"
              :maxlength="50"
            ></el-input>
          </el-form-item>
          <el-form-item label="身份证号：" prop="legalIdCard">
            <el-input
              v-model.trim="form.legalIdCard"
              placeholder="法人代表身份证号"
              :maxlength="18"
            ></el-input>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <div slot="footer">
      <el-button type="primary" @click="save">提交申请认证</el-button>
    </div>
  </wf-el-drawer>
</template>

<script>
  import { mapGetters } from 'vuex';
  import { regionData, codeToText } from '@/utils/area';
  import { isCertificateImg, isCardID } from '@/utils/regExpUtil';

  import { getOrgInfo, updateOrgInfo } from '@/api/organization';
  import { uploadImg } from '@/api/upload';

  export default {
    data() {
      const validateIdCard = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入法人代表身份证号'));
          return;
        }
        if (!isCardID(value)) {
          callback(new Error('身份证号格式不正确'));
          return;
        }
        callback();
      };
      return {
        visible: false,
        areaOptions: regionData,
        selectedArea: [],
        fileList: [],
        rawData: {
          province: 0, // 省
          provinceName: '',
          city: 0, // 省
          cityName: '',
          district: 0, // 省
          districtName: '',
          address: '',
          creditCode: '',
          legalIdCard: '',
          legalPerson: '',
          licenseImg: '',
          organizationName: '',
        },
        form: {},
        rules: {
          // deptName: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
          organizationName: [{ required: true, message: '请输入企业名称', trigger: 'change' }],
          address: [{ required: true, message: '请输入企业地址', trigger: 'change' }],
          creditCode: [{ required: true, message: '请输入证件号码', trigger: 'change' }],
          licenseImg: [{ required: true, message: '请上传营业执照', trigger: 'change' }],
          legalPerson: [{ required: true, message: '法人代表姓名', trigger: 'change' }],
          legalIdCard: [{ required: true, validator: validateIdCard, trigger: 'change' }],
        },
      };
    },
    computed: {
      ...mapGetters('user', ['userInfo']),
      isClient() {
        return !!this.userInfo.isClient || false;
      },
    },
    methods: {
      async onOpen(organizationId) {
        const { data } = await getOrgInfo(organizationId); //获取企业接口数据
        this.form = Object.keys(this.rawData).reduce(
          (col, key) => ({ ...col, [key]: data[key] }),
          {}
        );
        this.form.organizationId = organizationId;
        const licenseImg = data.licenseImg;
        this.fileList = licenseImg
          ? [{ name: licenseImg.replace(/^.*\//, ''), url: licenseImg }]
          : [];
        this.selectedArea = data.district
          ? [`${data.province}`, `${data.city}`, `${data.district}`]
          : [];
        this.visible = true;
      },
      async save() {
        this.$refs['form'].validate(async valid => {
          if (valid) {
            const { data } = await updateOrgInfo(this.form);
            data ? this.$message.success('认证成功') : this.$message.error('认证不通过');
            this.cancel();
            this.$emit('saved');
          }
        });
      },
      cancel() {
        this.visible = false;
        this.selectedArea = [];
        this.fileList = [];
        this.$refs['form'].resetFields();
      },
      handleAreaChange(selectedOptions) {
        this.selectedArea = selectedOptions;
        const [province = '', city = '', district = ''] = selectedOptions;
        const [provinceName = '', cityName = '', districtName = ''] = [
          codeToText[province],
          codeToText[city],
          codeToText[district],
        ];
        this.form = {
          ...this.form,
          province,
          city,
          district,
          provinceName,
          cityName,
          districtName,
        };
      },
      beforeUpload(file) {
        const isImg = isCertificateImg(file.name);
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isImg) {
          this.$message.error('支持格式：jpg、jpeg、png、bmp、gif');
        }
        if (!isLt5M) {
          this.$message.error('文件大小不超过5M');
        }
        if (isImg && isLt5M) {
          this.onUpload(file);
        }
        return false;
      },
      onUploadSuccess(res) {
        this.$refs['uploadImg'].clearValidate();
        const { filePath, originName } = res.data;
        this.form.licenseImg = filePath;
        this.fileList.push({
          name: originName,
          url: filePath,
        });
      },
      onUploadRemove() {
        this.fileList = [];
      },
      beforeClose(done) {
        this.cancel();
        done();
      },
      async onUpload(file) {
        let _flie = file;
        if (this.isClient) {
          const { electronReadFile } = require('@/utils/electronUpload');
          _flie = await electronReadFile(_flie.path);
        }
        const formData = new FormData(); //创建form对象
        formData.append('file', _flie);
        const res = await uploadImg(formData);
        this.onUploadSuccess(res);
      },
    },
  };
</script>

<style lang="scss" scoped>
  .org-auth-drawer-box-label {
    margin-bottom: 20px;
    font-weight: bold;
  }
  .org-auth-drawer-foot {
    border-top: 1px solid #f7f6f9;
    text-align: right;
    padding: 20px 30px;
  }
  .org-auth-area {
    padding-bottom: 10px;
  }

  .org-auth-upload-tip {
    color: #7f848b;
    > span {
      padding-bottom: 10px 0;
      display: inline-block;
    }
  }
</style>
<style lang="scss">
  .org-auth-upload.has-upload {
    .el-upload {
      display: none;
    }
  }
</style>
